package com.hankol.material.viewmodel

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.content.Context
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.appbar.AppBarLayout
import com.hankol.material.api.MaterialConstants
import com.hankol.material.bean.*
import com.hankol.material.fragment.ContentListFragment
import com.hankol.material.respository.MaterialReqManager
import java.util.*

/**
 * @author 关忆北丶
 * @description:
 * @date :2021/6/21 14:18
 */
class MaterialContentViewModel : MaterialBaseViewModel() {
    var mOnScrollStateChanged: OnScrollStateChanged? = null
    var screenList: MutableLiveData<List<LevelOneBean>> = MutableLiveData()
    var contentInfoList: MutableLiveData<MaterialContentInfo> = MutableLiveData()
    var tabInfoList: MutableLiveData<MaterialContentInfo> = MutableLiveData()
    private var animaIng: Boolean = false
    /**
     * 更新三级目录
     */
    fun upTertiaryData() {

    }

    /**
     * 更新四级目录
     */
    fun upLevelData() {

    }

    fun getListPosition(mList: ArrayList<MaterialTabBean>, type: Int): Int {
        var position: Int = -1
        for (index in 0 until mList.size) {
            if (mList[index].type == type) {
                position = index
                break
            }
        }
        return position
    }

    fun loadScreenBean(categoryId: Long): MaterialBusinessBean {
        return MaterialBusinessBean(MaterialConstants.BUSINESS_TYPE_SCREEN, "", categoryId, 0L, 0)
    }

    /**
     *
     */
    fun handlerData(bean: MaterialBusinessBean) {
        when (bean.type) {
            MaterialConstants.BUSINESS_TYPE_SCREEN -> {
                reqCatalogueList(bean.categoryId, TabConfigure.ALL.tabConfig, 1)
            }

            MaterialConstants.BUSINESS_TYPE_SEARCH -> {
                reqSearch(bean.searchContent, TabConfigure.ALL.tabConfig, 1)
            }

            MaterialConstants.BUSINESS_TYPE_FOLDER -> {
                reqFolderList(bean.collectionId, TabConfigure.ALL.tabConfig, 1)
            }
        }
    }

    /**
     *跟新tab数量
     */
    fun handlerTab(bean: MaterialBusinessBean) {
        when (bean.type) {
            MaterialConstants.BUSINESS_TYPE_SCREEN -> {
                reqTabInfo(bean.categoryId, TabConfigure.ALL.tabConfig, 1)
            }

            MaterialConstants.BUSINESS_TYPE_SEARCH -> {
                reqSearchTabInfo(bean.searchContent, TabConfigure.ALL.tabConfig, 1)
            }

            MaterialConstants.BUSINESS_TYPE_FOLDER -> {
                reqFolderTabInfo(bean.collectionId, TabConfigure.ALL.tabConfig, 1)
            }
        }
    }

    /**
     *
     */
    fun handlerData(bean: MaterialBusinessBean, mediaType: Int, page: Int) {
        when (bean.type) {
            MaterialConstants.BUSINESS_TYPE_SCREEN -> {
                reqCatalogueList(bean.categoryId, mediaType, page)
            }

            MaterialConstants.BUSINESS_TYPE_SEARCH -> {
                reqSearch(bean.searchContent, mediaType, page)
            }

            MaterialConstants.BUSINESS_TYPE_FOLDER -> {
                reqFolderList(bean.collectionId, mediaType, page)
            }
        }
    }

    fun setEmpty(bean: MaterialBusinessBean, rvView: LinearLayout, tvView: TextView) {
        rvView.visibility = View.GONE
        tvView.visibility = View.VISIBLE
        when (bean.type) {
            MaterialConstants.BUSINESS_TYPE_SCREEN -> {
                tvView.text = "未查找内容~"//目录筛选
            }

            MaterialConstants.BUSINESS_TYPE_SEARCH -> {
                tvView.text = "没有搜到，换个词试试~"//搜索
            }

            MaterialConstants.BUSINESS_TYPE_FOLDER -> {
                tvView.text = "没有收藏内容~"//收藏夹
            }
        }
    }

    fun getLinearLayout(context: Context): LinearLayoutManager {
        return LinearLayoutManager(context)
    }

    fun getGridLayout(context: Context, spanCount: Int): GridLayoutManager {
        return GridLayoutManager(context, spanCount)

    }

    fun chanageData(beanList: List<LevelOneBean>): List<LevelOneBean> {
        return if (beanList.isNotEmpty()) {
            val toMutableList = beanList.toMutableList()
            val list = emptyList<LevelOneBean>()
            val bean = LevelOneBean(list, "", 0L, 0L, 0, 0, "全部", 0L, true)
            toMutableList.add(0, bean)
            toMutableList
        } else {
            beanList
        }
    }

    fun screenVisible(fragment: ContentListFragment, recyclerView: RecyclerView, topView: LinearLayout, appBar: AppBarLayout?) {
        var screenShowCount: Int = 0//一屏能展示的item条数
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                val layoutManager = recyclerView.layoutManager
                //判断是当前layoutManager是否为LinearLayoutManager
                // 只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
                if (layoutManager is LinearLayoutManager) {
                    val linearManager = layoutManager as LinearLayoutManager?
                    linearManager?.let {
                        val firstItemPosition = linearManager.findFirstVisibleItemPosition()//屏幕第一个

                        val lastItemPosition = it.findLastVisibleItemPosition()//屏幕最后一个
                        screenShowCount = lastItemPosition - firstItemPosition
                        if (!animaIng && topView.visibility == View.GONE && lastItemPosition > screenShowCount * 2) {
                            animaIng = true
                            showView(topView)
                        } else if (!animaIng && topView.visibility == View.VISIBLE && lastItemPosition < screenShowCount * 2) {
                            animaIng = true
                            hiddenView(topView)
                        }


                        if (firstItemPosition == 0 && fragment.isGoTop) {
                            appBar?.setExpanded(true, true)
                            fragment.isGoTop = false
                        }
                        mOnScrollStateChanged?.onStateChanged(firstItemPosition, lastItemPosition)
                    }
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
            }
        })
    }

    /**
     * 素材库搜索
     */
    fun reqSearch(searchContent: String, type: Int, page: Int) {
        MaterialReqManager.getInstance().reqSearch(contentInfoList, searchContent, page, type)
    }

    /**
     * 素材库搜索 tab 信息更新
     */
    fun reqSearchTabInfo(searchContent: String, type: Int, page: Int) {
        MaterialReqManager.getInstance().reqSearch(tabInfoList, searchContent, page, type)
    }

    /**
     * 素材库筛选tab信息更新
     */
    fun reqTabInfo(categoryId: Long, type: Int, page: Int) {
        MaterialReqManager.getInstance().reqCatalogueList(tabInfoList, categoryId, page, type)
    }

    /**
     * 资料夹详情 tab信息更新
     */
    fun reqFolderTabInfo(collectionId: Long, type: Int, page: Int) {
        MaterialReqManager.getInstance().reqFolderList(tabInfoList, collectionId, page, type)
    }


    /**
     * 素材库筛选内容详情
     */
    fun reqCatalogueList(categoryId: Long, type: Int, page: Int) {
        MaterialReqManager.getInstance().reqCatalogueList(contentInfoList, categoryId, page, type)
    }


    /**
     * 资料夹详情
     */
    fun reqFolderList(collectionId: Long, type: Int, page: Int) {
        MaterialReqManager.getInstance().reqFolderList(contentInfoList, collectionId, page, type)
    }


    //素材库目录列表
    fun reqMateriaScreenlList(id: Long) {
        MaterialReqManager.getInstance().getMaterialCatalogueList(screenList, id)
    }


    fun showView(view: View) {
        //为加载视图设置动画，使其不透明度为0％。动画结束后，将其可见性设置为GONE作为优化步骤（它将不参与布局传递，等等）.
        view.animate()
                .alpha(1f)
                .setDuration((1.5 * 1000).toLong()) //动画持续时间 毫秒单位
                .setListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationStart(animation: Animator?) {
                        super.onAnimationStart(animation)

                    }

                    override fun onAnimationEnd(animation: Animator) {
                        view.visibility = View.VISIBLE
                        animaIng = false
                    }
                })
    }

    fun hiddenView(view: View) {
        //为加载视图设置动画，使其不透明度为0％。动画结束后，将其可见性设置为GONE作为优化步骤（它将不参与布局传递，等等）.
        view.animate()
                .alpha(0f)
                .setDuration((1.5 * 1000).toLong()) //动画持续时间 毫秒单位
                .setListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator) {
                        view.visibility = View.GONE
                        animaIng = false
                    }
                })
    }




    interface OnScrollStateChanged {
        fun onStateChanged(startPosition: Int, endPosition: Int)
    }
}